import type { NumberStatisticOptionState, AssetOverviewState, NumberStatisticItem } from './typings'
import { defineComponent, ref, onMounted } from 'vue'
import { ElDialog, ElButton, ElCard, ElRow, ElCol, ElLink, ElImage, ElSpace } from 'element-plus'
import { useStore } from 'vuex'
// import AliIcon from '~/components/AliIocn' // 阿里巴巴图标库
import styles from './index.module.scss'

export default defineComponent({
  name: 'NumberStatisticOption',
  props: ['visible'],
  emits: ['cancel', 'getNumberStatisticDatas'],
  setup(props: NumberStatisticOptionState, { emit }) {
    const store = useStore()
    const numberStatisticDatas = ref<AssetOverviewState['numberStatistic']>()
    // const numPerRow = ref() // 一行显示个数
    const userInfo = JSON.parse(localStorage.getItem('saber-userInfo')!) // 获取当前登录人

    onMounted(() => {
      getCardsShowAndHidden()
      // getNumPerRow()
    })

    // 数量统计 所有卡片
    const getCardsShowAndHidden = async () => {
      const info = JSON.parse(
        localStorage.getItem(`assetOverviewNumberInfo${userInfo.content.userId}`)!
      )
      const res = await store.dispatch('assetOverview/GetAssetModelList')
      if (res?.code === 200) {
        let ifUpdate = false // 是否更新缓存
        if (!info || (info && info.length !== res.data.length)) {
          emit('getNumberStatisticDatas', true) // 更新数量统计的显示
        } else if (info && info.length === res.data.length) {
          const infoCode = info.map((item: { code: string }) => item.code) // 已缓存的code
          const newCode = res.data.map((item: { code: string }) => item.code) // 当前接口最新code
          // 比较两者内容是否一致, 顺序不计
          for (let i = 0; i < infoCode.length; i++) {
            if (newCode.indexOf(infoCode[i]) !== -1) {
              ifUpdate = true
              break
            }
          }

          // 是否更新缓存
          if (ifUpdate) {
            numberStatisticDatas.value = info
          } else {
            emit('getNumberStatisticDatas', true) // 即使有缓存也更新数量统计
          }
        }
      }
    }

    // 一行显示个数
    // const getNumPerRow = () => {
    //   const numberStatisticCard = document.getElementById('numberStatisticCard')?.clientWidth ?? 0 // 卡片宽
    //   const numberStatisticExpand =
    //     document.getElementById('numberStatisticExpand')?.clientWidth ?? 0 // 展开宽
    //   // 一行显示几个
    //   numPerRow.value = Math.floor(numberStatisticExpand / (numberStatisticCard + 19)) - 1 // 19是卡片margin右边距
    // }

    // 卡片显隐
    const handelShowAndHiddenCards = (record: NumberStatisticItem) => {
      for (let i = 0; i < numberStatisticDatas.value!.length; i++) {
        const item = numberStatisticDatas.value![i]
        if (item.code === record.code) {
          item.show = !item.show
          break
        }
      }
    }

    // 卡片显隐 做本地浏览器缓存
    const cardsShowAndHiddenSubmit = () => {
      window.localStorage.setItem(
        `assetOverviewNumberInfo${userInfo.content.userId}`,
        JSON.stringify(numberStatisticDatas.value)
      ) // 更新所有

      // 上次缓存显示的数据
      const orderInfo = JSON.parse(
        localStorage.getItem(`assetOverviewNumberOrder${userInfo.content.userId}`)!
      )

      for (let i = 0; i < numberStatisticDatas.value!.length; i++) {
        let hasCode = false
        // 数组对象的属性code是否已存在相同值
        const item = numberStatisticDatas.value![i]
        for (let j = 0; j < orderInfo.length; j++) {
          const element = orderInfo[j]
          if (item.code === element.code) {
            hasCode = true
            break
          }
        }

        if (hasCode && !item.show) {
          // 已存在于原显示数据中, 且现在要隐藏
          for (let j = 0; j < orderInfo.length; j++) {
            const element = orderInfo[j]
            if (item.code === element.code) {
              orderInfo.splice(j, 1)
            }
          }
        } else if (!hasCode && item.show) {
          // 未存在于原显示数据中
          orderInfo.push(item)
        }
      }

      window.localStorage.setItem(
        `assetOverviewNumberOrder${userInfo.content.userId}`,
        JSON.stringify(orderInfo)
      ) // 加存要显示的

      emit('getNumberStatisticDatas', false) // 更新数量统计的显示
      emit('cancel') // 返回
    }

    return () => {
      return (
        <div class={styles['number-statistic-ElDialog']}>
          <ElDialog
            title="自定义卡片"
            width="52%"
            modelValue={props.visible}
            closeOnClickModal={false} // 点遮罩层不关弹窗
            draggable // 可拖拽
            beforeClose={() => emit('cancel')}
          >
            <div class={styles['number-statistic']}>
              <ElSpace size={20} wrap>
                {numberStatisticDatas.value &&
                  numberStatisticDatas.value!.map((item) => (
                    <div onClick={() => handelShowAndHiddenCards(item)}>
                      <ElCard
                        shadow="hover"
                        class={{
                          [styles['number-statistic-cards']]: true
                          // [styles['number-statistic-cards-margin']]: index % numPerRow.value === 2
                        }}
                        style={`background-image: ${item.backgroundImage};`}
                      >
                        <ElRow>
                          <ElCol span={17} class={styles['number-statistic-cards-words']}>
                            <div class={styles['number-statistic-cards-data']}>
                              <ElLink
                                underline={false}
                                class={styles['number-statistic-cards-num']}
                              >
                                ###
                              </ElLink>
                              &nbsp;
                              <span class={styles['number-statistic-cards-unit']}>{item.unit}</span>
                            </div>
                            <span class={styles['number-statistic-cards-name']}>{item.name}</span>
                          </ElCol>
                          <ElCol span={7}>
                            <div class={styles['number-statistic-cards-icon']}>
                              {/* <AliIcon type={item.icon!} /> // icon暂用切图, 阿里图标库上传好了再换这句 */}
                              <ElImage src={item.iconImage!} />
                            </div>
                          </ElCol>
                        </ElRow>
                        {/* 显隐 */}
                        {item.show && (
                          <span class={styles['number-statistic-cards-show']}>
                            {/* <AliIcon type="icon-tupianshangchuan" /> // icon暂用切图, 阿里图标库上传好了再换这句 */}
                            <ElImage
                              src={'/assetOverview/temporaryIconImage/numberStatisticOption.png'}
                            />
                          </span>
                        )}
                      </ElCard>
                    </div>
                  ))}
              </ElSpace>
            </div>

            <div class={styles['confirm-button']}>
              <ElButton
                size={'default'}
                onClick={() => emit('cancel')}
                class={styles['confirm-button-cancel']}
              >
                取 消
              </ElButton>
              <ElButton
                type="primary"
                size={'default'}
                onClick={cardsShowAndHiddenSubmit}
                class={styles['confirm-button-submit']}
              >
                确 定
              </ElButton>
            </div>
          </ElDialog>
        </div>
      )
    }
  }
})
